<template>
  <div id="index">
    <div class="app-container" id="container">

      <el-form ref="form" :model="form" :rules="rules" label-width="140px" label-position="right">
        <div class="product-div">
          <div class="product-header">
            <em style="font-size: 18px;font-style: normal;" class="big_title_style">基本信息</em>
          </div>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="套餐卡名称" prop="cardName">
                {{ form.cardName }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="服务套餐卡分类" prop="categoryUids" style="width: 100%;">
                {{ form.categoryUidsStr }}
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>
            <el-col :span="7">
              <el-form-item label="服务套餐卡类别" prop="cardType" style="width: 100%;">
                {{ form.cardTypeStr }}

              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="服务耗时" prop="cardServiceDuration">
                {{ form.cardServiceDuration }}分钟
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">分钟</div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="面价" :required="true">
                {{ form.cardPriceStr }}元
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="活动价格" prop="itemFavorablePrice">
                {{ form.cardFavorablePriceStr }}元
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="菠萝派" prop="cardBoluoHuaPrice">
                {{ form.cardBoluoHuaPriceStr }}个
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">个</div>
            </el-col>
            
          </el-row>


          <el-row :gutter="20">
            

            <el-col :span="7">
              <el-form-item label="门店销售分成" :required="true">
                {{ form.cardSalePercent }}%
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">%</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="门店服务分成" :required="true">
                {{ form.cardServicePercent }}%
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">%</div>
            </el-col>
			
			<el-col :span="7">
			  <el-form-item label="限制使用次数" prop="expireDay">
			    {{ form.limitUseTimes }}
			  </el-form-item>
			</el-col>
			<el-col :span="1">
			  <div class="div-appendHide">天</div>
			</el-col>
          </el-row>

          <el-row :gutter="24">

           

            <el-col :span="14">
              <el-form-item label="过期类型" prop="itemServiceDuration">
                <span>{{ form.expireDate ? form.expireDate:form.expireDay == -1  ? '长期有效':form.expireDay+'天' }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="适用门店">
                <!-- <el-checkbox-group v-model="form.serviceTypes" disabled>
                  <el-checkbox label="Life">生美</el-checkbox>
                  <el-checkbox label="Medical">医美</el-checkbox>
                  <el-checkbox label="probxplus">菠萝家</el-checkbox>
                </el-checkbox-group> -->

                <el-checkbox-group v-model="form.serviceTypes" disabled>
                  <el-checkbox :key="index"
                    v-for="(item, index) in serviceTypesList" :label="item.dictValue">
                    {{ item.dictLabel }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="选择">
                <el-checkbox-group v-model="form.checkList" disabled>
                  <el-checkbox label="isCommon">指定门店</el-checkbox>
                  <el-checkbox label="isSubgift">支持转赠</el-checkbox>
                  <el-checkbox label="isShow">前端展示</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="门店列表" v-if="existValue('isCommon') > 0" :required="true">
            <selected ref="childStore" style="margin-top: 10px;" v-if="selectedDataStore.length > 0"
              :selectedData="selectedDataStore">
            </selected>
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="支付方式">
                <el-checkbox-group v-model="form.checkListPay" disabled>
                  <el-checkbox label="isUseBoluoGoldCoin">菠萝金币</el-checkbox>
                  <el-checkbox label="isUseBoluoSilverCoin">菠萝银币</el-checkbox>
                  <el-checkbox label="isUseCoupon">优惠券</el-checkbox>
                  <el-checkbox label="isUseMemberDiscount">会员折扣</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="折扣等级" v-if="existValuePay('isUseMemberDiscount') > 0" :required="true">
                <el-select disabled style="width: 100%;" v-model="form.memberLevel" placeholder="请选择等级" clearable
                  size="small">
                  <el-option v-for="dict in levelOptions" :key="dict.customerGrade" :label="dict.levelName"
                    :value="dict.customerGrade" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="营销标签" prop="marketingTags" style="width: 100%;">
                {{ form.marketingTags }}
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="标签集合" prop="cardTags" style="width: 100%;">
                {{ form.cardTags }}
              </el-form-item>
            </el-col>

          </el-row>




          <el-form-item label="套餐主图" prop="itemMainImage">
            <el-image :z-index="zIndex" :preview-src-list="[form.cardMainImage]" :src="form.cardMainImage" style="
                      width: 80px;
                      height: 80px;
                      margin-left: 10px;
                      margin-top: 10px;
                      border: 1px solid #ebebeb;
                      border-radius: 6px;
                    ">
            </el-image>
          </el-form-item>

          <el-form-item label="套餐背景图" prop="backgroundImage">
            <el-image :z-index="zIndex" :preview-src-list="[form.backgroundImage]" :src="form.backgroundImage" style="
                      width: 80px;
                      height: 80px;
                      margin-left: 10px;
                      margin-top: 10px;
                      border: 1px solid #ebebeb;
                      border-radius: 6px;
                    ">
            </el-image>
          </el-form-item>

          <el-form-item label="套餐轮播图" prop="cardBannerStr">
            <el-image v-if="form.cardBanner" :z-index="zIndex" :preview-src-list="form.cardBannerStr"
              v-for="(imgm, index) in form.cardBannerStr" :src="imgm" :key="index" style="
                      width: 80px;
                      height: 80px;
                      margin-left: 10px;
                      margin-top: 10px;
                      border: 1px solid #ebebeb;
                      border-radius: 6px;
                    ">
            </el-image>

          </el-form-item>
          <el-row :gutter="24">
            <el-col :span="22">
              <el-form-item label="套餐文字描述" prop="itemDescText">
                {{ form.cardDescText }}
              </el-form-item>
            </el-col>
          </el-row>


          <el-form-item label="套餐图片" prop="cardDescImage">
            <el-image v-if="form.cardDescImage" :z-index="zIndex" :preview-src-list="form.cardDescImageStr"
              v-for="(imgm, index) in form.cardDescImageStr" :src="imgm" :key="index" style="
                      width: 80px;
                      height: 80px;
                      margin-left: 10px;
                      margin-top: 10px;
                      border: 1px solid #ebebeb;
                      border-radius: 6px;
                    ">
            </el-image>
          </el-form-item>


          <el-row :gutter="24">
            <el-col :span="22">
              <el-form-item label="特别提示" prop="itemTips">
                {{ form.cardTips }}
              </el-form-item>
            </el-col>
          </el-row>



        </div>


        <div class="product-div-two">
          <div class="product-header">
            <em style="font-size: 18px;font-style: normal;" class="big_title_style">服务套餐</em>
          </div>
          <div style="width: 1200px;padding: 10px 10px 20px 100px;">
            <selectedItemUpdate :canDelete="false" ref="childDevice" style="margin-top: 10px;"
              v-if="selectedDataDevice.length > 0" :selectedData="selectedDataDevice">
            </selectedItemUpdate>
          </div>

        </div>



      </el-form>
      <div class="dw">
        <el-button @click="colsePro" style="margin-top: 10px;margin-left: 40%;">返回</el-button>
      </div>
    </div>

    <commodityStore v-if="storeOpen" @toCloseBox="toCloseBox" @multipleSelection="multipleSelection" :flag="storeOpen"
      :source="false" ref="selTable"></commodityStore>

    <commodityItem v-if="deviceOpen" @toCloseBox="toCloseDeviceBox" @multipleSelection="multipleSelectionDevice"
      :flag="deviceOpen" :cardUid="cardUid" :source="false" ref="selTableDevice"></commodityItem>


  </div>
</template>

<script>
import {
  checkPermi,
  checkRole
}
  from "@/utils/permission"; // 权限判断函数
import {
  selectOptions
}
  from "@/api/service/serviceCategory";

import imageArraySize from "@/components/ImageUpload/imageArraySize";
import videoUpload from "@/components/ImageUpload/videoUpload";
import sku from "@/components/sku/index"
import {
  getCard, addCard, editCard
}
  from '@/api/service/card'

import selected from "@/components/Activity/SelectedStore";
import commodityStore from "@/components/Activity/commodityStore";


import selectedItemUpdate from "@/components/Activity/SelectedItemUpdate";
import commodityItem from "@/components/Activity/commodityItem";




export default {
  components: {
    imageArraySize,
    videoUpload,
    sku, selected,
    commodityStore, commodityItem, selectedItemUpdate
  },
  data() {
    return {
      zIndex: 2000,
      cardUid: this.$route.params.cardId,
      storeOpen: false,
      selectedDataStore: [],
      deviceOpen: false,
      selectedDataDevice: [],
      indexs: 0,
      inputVisible: false,
      inputValue: '',
      roles: 0,
      roleRule: 0,
      // th 值；动态控制 th 标题、批量设置
      //规格名称和的值, 组件里面可以添加规格名称和值
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 商品类别
      categoryOptions: [],
      cardTypeOptions: [],

      // 更多的下拉
      displayBool: 0,
      // 查询参数
      queryParams: {},
      columns: [],
      // 表单参数
      form: {
        isCommon: '1',
        isLockDevice: '0',
        isUseBoluoGoldCoin: '0',
        isUseBoluoSilverCoin: '0',
        isUseCoupon: '0',
        isRecommend: '0',
        cardTagsArray: [],
        proboxServiceItemSkus: [],
        cardPriceStr: '0',
        cardFavorablePriceStr: '0',
        cardSettlementPriceStr: '0',
        cardBoluoHuaPriceStr: '0',
        isSubgift: '0',
      },
      property: [],
      propertyUid: [],
      // 表单校验
      rules: {
        cardName: [{
          required: true,
          message: "套餐卡名称不能为空",
          trigger: "blur"
        }],
        categoryUids: [{
          required: true,
          message: "套餐卡分类不能为空",
          trigger: "blur"
        }],
        cardType: [{
          required: true,
          message: "套餐卡类别不能为空",
          trigger: "blur"
        }],
        cardServiceDuration: [{
          required: true,
          message: "单服务耗时不能为空",
          trigger: "blur"
        }],
        cardComposeDuration: [{
          required: true,
          message: "组合服务耗时不能为空",
          trigger: "blur"
        }],
      },
      datas: [],
      tables: [],
      notNor: 0, //第一次不发生变化
      serviceTypesList:[],
    };
  },
  created() {
    let $this = this
    $this.bulidSelect();

    const cardId = $this.$route.params && $this.$route.params.cardId;
    this.getDicts("item_apply_store_type").then(response => {
        this.serviceTypesList = response.data;
      });
    if (cardId) {
      getCard(cardId).then(response => {
        $this.form = response.data
        $this.selectedDataStore = response.data.releaseList || []
        $this.selectedDataDevice = response.data.itemVoList || []
        $this.displayBool = 1;
        this.$set(this.form, 'checkList', [])
        this.$set(this.form, 'checkListPay', [])
        this.$set(this.form, 'serviceTypes', [])

        if (this.form.isCommon == '0') {
          this.form.checkList.push('isCommon');
        }
        if (this.form.isSubgift == '1') {
          this.form.checkList.push('isSubgift');
        }
        if (this.form.isShow == '1') {
          this.form.checkList.push('isShow');
        }
        if (this.form.isRecommend == '1') {
          this.form.checkList.push('isRecommend');
        }

        if (this.form.isUseCoupon == '1') {
          this.form.checkListPay.push('isUseCoupon');
        }
        if (this.form.isUseMemberDiscount == '1') {
          this.form.checkListPay.push('isUseMemberDiscount');
        }
        if (this.form.isUseBoluoGoldCoin == '1') {
          this.form.checkListPay.push('isUseBoluoGoldCoin');
        }
        if (this.form.isUseBoluoSilverCoin == '1') {
          this.form.checkListPay.push('isUseBoluoSilverCoin');
        }
        if (this.form.applyStoreType) {
          this.form.serviceTypes = this.form.applyStoreType.split(",")
        }
        // 分类
        selectOptions().then(response => {
          this.categoryOptions = response.data;
          if ($this.form.categoryUids) {
            let str = "";
            this.categoryOptions.forEach(vo => {

              if (vo.value == $this.form.categoryUids[0]) {
                str = vo.label;
                if ($this.form.categoryUids.length > 1 && vo.children) {
                  vo.children.forEach(it => {
                    if (it.value == $this.form.categoryUids[1]) {
                      str = str + "-" + it.label
                    }
                  })
                }
              }
            })
            this.$set(this.form, 'categoryUidsStr', '')
            $this.form.categoryUidsStr = str;
          }
        });
      });
    }


  },

  methods: {
    checkPermi,
    checkRole,
    existValue(type) {
      let index = 0;
      if (this.form.checkList) {
        this.form.checkList.forEach(elemet => {
          if (elemet == type) {
            index++;
          }
        })
      }

      return index;
    },
    existValuePay(type) {
      let index = 0;
      if (this.form.checkListPay) {
        this.form.checkList.forEach(elemet => {
          if (elemet == type) {
            index++;
          }
        })
      }

      return index;
    },
    selectCommodityDevice() {
      this.$forceUpdate()
      this.deviceOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableDevice"].greet(this.selectedDataDevice);
      });
    },
    selectCommodity() {
      this.$forceUpdate()
      this.storeOpen = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedDataStore);
      });
    },
    multipleSelectionDevice(data) {
      this.deviceOpen = false
      this.selectedDataDevice = data;
      this.$nextTick(() => {
        //this.$refs.childDevice.getList();
      });
    },
    multipleSelection(data) {
      this.storeOpen = false
      this.selectedDataStore = data;
      this.$nextTick(() => {
        ///this.$refs.childStore.getList();
      });
    },
    toCloseDeviceBox() {
      this.deviceOpen = false;
    },
    toCloseBox() {
      this.storeOpen = false;
    },
    indexMethod(index) {
      this.indexs = index
      return index * 1;
    },
    handleDelete(row, index) {
      console.log(index)
      if (row.skuId) {
        delSku(row.skuId).then(response => {
          this.form.proboxServiceItemSkus.splice(index, 1);

        })
      } else {
        this.form.proboxServiceItemSkus.splice(index, 1);

      }
    },
    handleAdd() {
      let data = {
        no: JSON.parse(JSON.stringify(this.indexs)),
        skuId: null,
        skuName: null,
        serviceItemId: null,
        cardPrice: 0,
        cardFavorablePrice: 0,
        cardSettlementPrice: 0,
        cardBoluoHuaPrice: 0,
        cardServiceDuration: 0,
        serviceTimes: 1,
      }
      this.form.proboxServiceItemSkus.push(data);
      console.log(this.form.proboxServiceItemSkus)
    },


    oninput(num, limit) {

      var str = num
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      if (len1 == ".") {
        str = ""
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位
        if (str.indexOf(".") == str.length - 1) {
          str = str.substring(0, str.length - 1);
        }
      }
      return str
    },
    oninputs(num, limit) {

      var str = num
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      if (len1 == ".") {
        str = ""
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位

      }
      return str
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    divShow(obj) {
      this.displayBool = obj;
    },
    /**各种下拉框 */
    bulidSelect() {

      this.getDicts("proBoxService_itemType").then(response => {
        this.cardTypeOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm(status) {
      console.log(this.form)

      this.$refs.child.selectImg();
      this.$refs.childss.selectImg();
      this.$refs.childsss.selectImg();
      if (this.form.cardMainImage == null || this.form.cardMainImage == "") {
        this.$message.error("请上传一张套餐卡主图");
        return;
      }
      if (this.form.cardBanner == null || this.form.cardBanner == "") {
        this.$message.error("请上传一张banner图片");
        return;
      }
      if (this.selectedDataDevice.length == 0) {
        this.$message.error("请选择一个服务套餐");
        return;
      }
      this.$refs["form"].validate(valid => {

        if (valid) {
          let qf = [];
          this.selectedDataStore.forEach(vo => {
            qf.push(vo.storeUid);
          })
          // let qfDevice = [];
          // this.selectedDataDevice.forEach(vo => {
          //   qfDevice.push(vo.deviceId);
          // })
          //this.form.deviceIdS = qfDevice;
          this.form.shopListIds = qf;
          //this.form.itemVoList = this.selectedDataDevice;
          const cardId = this.$route.params && this.$route.params.cardId;
          this.form.itemVoList = []
          this.form.cardId = cardId;
          this.selectedDataDevice.forEach(vo => {
            vo.itemPriceView = vo.itemPriceStr
            vo.itemFavorablePriceView = vo.itemFavorablePriceStr
            vo.itemSettlementPriceView = vo.itemSettlementPriceStr
            this.form.itemVoList.push(vo);
          })

          this.form.cardPriceView = this.form.cardPriceStr
          this.form.cardFavorablePriceView = this.form.cardFavorablePriceStr
          this.form.cardSettlementPriceView = this.form.cardSettlementPriceStr
          this.form.cardBoluoHuaPriceView = this.form.cardBoluoHuaPriceStr
          this.form.auditStatus = status;
          if (cardId) {


            editCard(this.form).then(respone => {
              this.msgSuccess("修改成功");
              this.colsePro();
            })
          } else {
            addCard(this.form).then(respone => {
              this.msgSuccess("添加成功");
              this.colsePro();
            })
          }
        }
      });
    },
    colsePro() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/product/card",
        query: {
          t: Date.now()
        }
      });
    },
    handleClose(tag) {
      this.form.cardTagsArray.splice(this.form.cardTagsArray.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.cardTagsArray.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  }
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 50%;
}

#photo {
  float: left;
  width: 70%;
}

#content {
  float: right;
  width: 30%;
}

.product-header {
  position: absolute;
  top: 0;
  width: 600px;
  padding: 18px;
  background-color: #fff;
  -moz-border-radius: 4px;
  border-radius: 4px;
  height: 40px;
}

.product-div {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 50px;
}

.product-div-two {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 60px;
}

.product-div-three {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 100px;
}

.place-font {
  color: #999;
  font-size: 13px;
  position: relative;
}

.dw {
  border: 1px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 200;
  padding-left: 120px;
  background-color: #FFF;
  border-top: 1px solid #eee;
  width: 100%;
  height: 55px;
}

.div-img {
  display: none;
}

.div-text {
  margin: 22px 0px 12px 120px;
  color: #2656bd;
  cursor: pointer;
  font-size: 13px;
}

.div-appendHide {
  line-height: 34px;
  font-size: 14px;
  color: #606266;
  margin-left: -50%;
  visibility: hidden;
}
</style >

